﻿package net.wangit.context;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
 * ActionContext创建工厂
 * @author watson
 *
 */
public class ActionContextFactory {

	private ActionContextFactory() {
	}

	public static ActionContext createActionContext(HttpServletRequest request,
			ServletContext servletContext) {
		ActionContextImpl ac = new ActionContextImpl();
		Map<String, String[]> requestMap = getRequestParameterMap(request);
		ac.setRequestParameterMap(requestMap);
		ac.setSessionMap(getSessionMap(request));
		ac.setServletContextMap(getServletContextAttributeMap(servletContext));
		if (request instanceof MultiPartRequestWrapper) {
			MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper) request;
			String inputName;
			Enumeration<String> fileParameterNames = multiWrapper
					.getFileParameterNames();
			while (fileParameterNames != null
					&& fileParameterNames.hasMoreElements()) {
				inputName = fileParameterNames.nextElement();
				ac.setFiles(inputName, multiWrapper.getFiles(inputName));
			}
		}
		return ac;
	}

	@SuppressWarnings("unchecked")
	private static Map<String, String[]> getRequestParameterMap(
			HttpServletRequest request) {
		return request.getParameterMap();
	}

	private static Map<String, Object> getSessionMap(HttpServletRequest request) {
		HttpSession session = request.getSession();
		HashMap<String, Object> map = new HashMap<String, Object>();
		String key;
		Enumeration<?> enumeration = session.getAttributeNames();
		while (enumeration.hasMoreElements()) {
			key = (String) enumeration.nextElement();
			map.put(key, session.getAttribute(key));
		}
		return map;
	}

	private static Map<String, Object> getServletContextAttributeMap(
			ServletContext servletContext) {
		Map<String, Object> map = new HashMap<String, Object>();
		String key;
		Enumeration<?> enumeration = servletContext.getAttributeNames();
		while (enumeration.hasMoreElements()) {
			key = enumeration.nextElement().toString();
			map.put(key, servletContext.getAttribute(key));
		}
		return map;
	}
}
